package com.example.mobileyd20313;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    //第一步：创建client对象
    public static OkHttpClient client;
	    static {//静态代码块 进行初始化
        	        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        	        builder.writeTimeout(15, TimeUnit.SECONDS);
        	        builder.readTimeout(15, TimeUnit.SECONDS);
        	        builder.connectTimeout(15, TimeUnit.SECONDS);
        	        client = builder.build();
        	    }
	    //第二步：创建RequestBody对象
        	    public static JSONObject buildJSON(String[] keys, Object... values){//构建JSON参数
                JSONObject jsonObject =null;
        	        try {
            	            jsonObject = new JSONObject();
            	            for (int i = 0; i < keys.length; ++i){
                	                jsonObject.put(keys[i], values[i]);
                	            }
            	        }catch (Exception e){
            	            jsonObject=null;
            	        }
        	        return jsonObject;
        	    }
	    public static RequestBody buildBody(JSONObject json) {//创建RequestBody对象
        	        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString());
        	    }
	    //第三步：创建Qequest对象
        	    public static String host = "http://121.9.253.237:8888/traffic/api/v2/";
	    public static Request buildRequest(String api, RequestBody body) {
        	        return new Request.Builder().url(host + api).post(body).build();
        	    }
	    //第四步：创建call对象
        	    public static Call buildCall(Request request) {
        	        return client.newCall(request);
        	    }
	    //第五步：通过Call#enqueue(Callback)方法来提交异步请求,并通过Handler将获取的数据提交给主线程处理

        	    public static Handler handler = new Handler(Looper.getMainLooper());//定义用于更新UI主线程的通讯句柄。
	//声明异步回调接口
        	    public interface AsyncCallBack {
	        void onFailure(Exception e);
	        void onResponse(String json);
	    }
	    public static void asyncRequest(final AsyncCallBack callBack, String api, String[] keys, String userName, String userPwd,Object...values){
        	        JSONObject jsonObject= buildJSON(keys, values);//将参数构建成绩JSON格式的数据
        	        RequestBody requestBody=buildBody(jsonObject);//获取RequestBody对象
        	        Request request = buildRequest(api, requestBody);//获取Request对象
        	        Call call=buildCall(request);//获得Call呼叫对象
        	        call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            callBack.onFailure(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String json = response.body().string();//获取反馈数据
                            handler.post(new Runnable() {//将对json数据的处理提交到主线
                                @Override
                                public void run() {
                                    callBack.onResponse(json);
                                }
                            });
                        }


        	        });  //将请求完成后的回调方法加到呼叫对象的队列中
        }

}
